package com.nemlistapp;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ShoppingListsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shopping_lists);
		States.getInstance().getPreferences(this);
		
		if(Connection.getInstance().checkNetwork(this))
		{
		ShoppingListsFetcher shoppingListsFetcher = new ShoppingListsFetcher(this);
		shoppingListsFetcher.execute(States.getInstance().getUserName());
		}
		else
		{
			//Get latest from device SQLite/States or show no connection message.
		}
	}
	
	public void setShoppingLists(ArrayList<ShoppingList> shoppingLists)
	{
		final ListView listView = (ListView) findViewById(R.id.shoppingListsList);
		try
		{
		ArrayAdapter<ShoppingList> shoppingListsAdapter = new ArrayAdapter<ShoppingList>(this, android.R.layout.simple_list_item_1, shoppingLists);
		listView.setTextFilterEnabled(true);
		listView.setAdapter(shoppingListsAdapter);
		shoppingListsAdapter.notifyDataSetChanged();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		listView.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View view,
	                int position, long id) {

	        	Object obj = listView.getItemAtPosition(position);
	        	ShoppingList shoppingList = (ShoppingList)obj;  
	        	openShoppingListActivity(shoppingList);
	        }
		});
	}
	
	private void openShoppingListActivity(ShoppingList shoppingList)
	{
		States.getInstance().setCurrentShoppingList(shoppingList);
		Intent intent = new Intent(this, ShoppingListActivity.class);
		startActivity(intent);
	}
}
